package com.bestom.waterquality.activity;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.drawerlayout.widget.DrawerLayout;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.provider.Settings;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.FrameLayout;
import android.widget.ImageView;

import com.bestom.waterquality.R;
import com.bestom.waterquality.adapter.IndicatorExpandableListAdapter;
import com.bestom.waterquality.entity.Constant;
import com.bestom.waterquality.logic.DeviceStatus;
import com.bestom.waterquality.logic.FactoryReset;
import com.bestom.waterquality.logic.SensorSet;
import com.bestom.waterquality.logic.SerialPortSet;
import com.bestom.waterquality.logic.IOSet;
import com.bestom.waterquality.logic.ImageSet;
import com.bestom.waterquality.logic.ImageViewer;
import com.bestom.waterquality.logic.MQttConfiguration;
import com.bestom.waterquality.logic.PeripheralStatus;
import com.bestom.waterquality.logic.RTSPSet;
import com.bestom.waterquality.logic.Reboot;
import com.bestom.waterquality.logic.RelaySet;
import com.bestom.waterquality.logic.SoftwareUpdate;
import com.bestom.waterquality.logic.WarningRecord;
import com.bestom.waterquality.logic.Wlan;
import com.bestom.waterquality.util.ToastUtil;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executors;

/**
 * @author shulman
 */
public class MainActivity extends BaseActivity {

    private DrawerLayout drawerLayout;
    private FrameLayout drawerLayoutFrame;
    private ImageView mImageView;
    private Context mContext;
    private AlertDialog alertDialog;

    private Activity mActivity;
    public static String viewText = "设备状态";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mContext = this;
        mActivity = this;
        // 初始化视图
        initView();
        // 初始化数据
        initData();
        if (Build.VERSION.SDK_INT >= 23) {
            int REQUEST_CODE_CONTACT = 101;
            String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};
            //验证是否许可权限
            for (String str : permissions) {
                if (this.checkSelfPermission(str) != PackageManager.PERMISSION_GRANTED) {
                    //申请权限
                    this.requestPermissions(permissions, REQUEST_CODE_CONTACT);
                }
            }
        }
        mkDir(Constant.realImageDir);
        mkDir(Constant.warningImageDir);
    }

    /**
     * 初始化视图
     */
    private void initView() {
        ImageView titleLeft = findViewById(R.id.title_left);
        titleLeft.setImageResource(R.drawable.list);
        titleLeft.setOnClickListener(view -> showDrawerLayout());

        View inflate = LayoutInflater.from(mContext).inflate(R.layout.image_view, null);
        mImageView = inflate.findViewById(R.id.image_view);
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setView(mImageView);
        alertDialog = builder.create();
        mImageView.setOnClickListener(view -> alertDialog.dismiss());

        drawerLayoutFrame = findViewById(R.id.drawer_layout_frame);
        drawerLayout = findViewById(R.id.drawer_layout);
        drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
            @Override
            public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
                // 设置图片旋转
                if (slideOffset > 0.1) titleLeft.setRotation((float) ((slideOffset - 0.1) * 100));
                else titleLeft.setRotation(0);
            }

            @Override
            public void onDrawerOpened(@NonNull View drawerView) {
            }

            @Override
            public void onDrawerClosed(@NonNull View drawerView) {
            }

            @Override
            public void onDrawerStateChanged(int newState) {
            }
        });
        final ExpandableListView listView = findViewById(R.id.expand_list);
        // 设置抽屉的宽度为当前屏幕的1/3
        listView.getLayoutParams().width = getWindowManager().getDefaultDisplay().getWidth() / 3;
        // 设置抽屉的内容
        final IndicatorExpandableListAdapter adapter = new IndicatorExpandableListAdapter(Constant.GROUP_NAMES, Constant.GROUP_ICONS, Constant.CHILD_NAMES, Constant.CHILD_ICONS, Constant.CHILD_COLOR_ICONS);
        listView.setAdapter(adapter);

        // 清除默认的 Indicator
        listView.setGroupIndicator(null);

        // 设置分组项的点击监听事件
        listView.setOnGroupClickListener((parent, v, groupPosition, id) -> {
            boolean groupExpanded = parent.isGroupExpanded(groupPosition);
            adapter.setIndicatorState(groupPosition, groupExpanded);
            // 请务必返回 false，否则分组不会展开
            return false;
        });

        // 设置子选项点击监听事件
        listView.setOnChildClickListener((parent, v, groupPosition, childPosition, id) -> {

            // viewText作为记录当前选项值，用于更新抽屉被选中后不一样的颜色
            viewText = Constant.CHILD_NAMES[groupPosition][childPosition];
            adapter.notifyDataSetChanged();
            // 点击抽屉选项后，更新主页面对应选项的视图
            resetView(mLayoutViewMap.get(viewText));
            return true;
        });
    }
    @SuppressLint("HandlerLeak")
    private final Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {

            Log.d("oo", String.valueOf(msg.obj));
            File file = new File(String.valueOf(msg.obj));
            if (file.exists()) {
                mImageView.setImageURI(Uri.fromFile(file));
                alertDialog.show();
            }else ToastUtil.toast("此图片不存在");
        }
    };

    /**
     * 递归创建文件夹
     */
    private void mkDir(String dirPath) {
        String[] dirArray = dirPath.split("/");
        String pathTemp = "";
        for (int i = 1; i < dirArray.length; i++) {
            pathTemp = pathTemp + "/" + dirArray[i];
            File newF = new File(dirArray[0] + pathTemp);
            if (!newF.exists()) {
                newF.mkdir();
            }
        }
    }

    /**
     * mLayoutViewMap
     * 用于存储加载的View，便于点击时不再重新加载，从而快速响应更新视图
     */
    private Map<String, View> mLayoutViewMap;

    /**
     * 初始化数据
     */
    private void initData() {

        if (mLayoutViewMap != null) return;
        mLayoutViewMap = new HashMap<>(20);
        // 程序运行初始化界面
        resetView(mLayoutViewMap.get(viewText));
        // 开启子线程去加载所有View，存储到mLayoutViewMap中
        Executors.newSingleThreadExecutor().execute(() -> {
            Looper.prepare();
            long l = System.currentTimeMillis();
            mLayoutViewMap.put("设备状态", LayoutInflater.from(mContext).inflate(R.layout.frament_device_state, null, false));
            mLayoutViewMap.put("外设状态", LayoutInflater.from(mContext).inflate(R.layout.frament_peripheral_state, null, false));

            View view0 = LayoutInflater.from(mContext).inflate(R.layout.frament_warning_record, null, false);
            mLayoutViewMap.put("预警记录", view0);
            WarningRecord.getInstance().setDataAndListen(mActivity, mContext, view0, mHandler);

            View view1 = LayoutInflater.from(mContext).inflate(R.layout.frament_image_viewer, null, false);
            mLayoutViewMap.put("图像查看", view1);
            ImageViewer.getInstance().setDataAndListen(mActivity, mContext, view1, mHandler);

            mLayoutViewMap.put("配置网络", LayoutInflater.from(mContext).inflate(R.layout.frament_network_set, null, false));

            View view2 = LayoutInflater.from(mContext).inflate(R.layout.frament_serial_set, null, false);
            mLayoutViewMap.put("串口设置", view2);
            SerialPortSet.getInstance().setDataAndListen(this, mContext, view2);

            mLayoutViewMap.put("继电器设置", LayoutInflater.from(mContext).inflate(R.layout.frament_relay_set, null, false));
            mLayoutViewMap.put("IO设置", LayoutInflater.from(mContext).inflate(R.layout.frament_io_set, null, false));
            mLayoutViewMap.put("MQTT配置", LayoutInflater.from(mContext).inflate(R.layout.frament_mqtt_configuration, null, false));
            mLayoutViewMap.put("图像设置", LayoutInflater.from(mContext).inflate(R.layout.frament_image_set, null, false));
            mLayoutViewMap.put("重新开机", LayoutInflater.from(mContext).inflate(R.layout.frament_reboot, null, false));
            mLayoutViewMap.put("恢复出厂设置", LayoutInflater.from(mContext).inflate(R.layout.frament_factory_reset, null, false));
            mLayoutViewMap.put("软件升级", LayoutInflater.from(mContext).inflate(R.layout.frament_software_update, null, false));
            mLayoutViewMap.put("传感器设置", LayoutInflater.from(mContext).inflate(R.layout.frament_sensor_set, null, false));
            mLayoutViewMap.put("RTSP设置", LayoutInflater.from(mContext).inflate(R.layout.frament_rtsp_set, null, false));
            long ll = System.currentTimeMillis();
            Log.d("execute", "time --->" + (ll - l));
            Looper.loop();
        });
    }


    /**
     * 抽屉打开或关闭
     */
    private void showDrawerLayout() {
        if (drawerLayout.isDrawerOpen(Gravity.LEFT)) {
            drawerLayout.closeDrawer(Gravity.LEFT);
        } else {
            drawerLayout.openDrawer(Gravity.LEFT);
        }
    }

    /**
     * 点击抽屉选项后，更新主页面对应选项的视图
     * view 要更新的视图文件
     */
    private void resetView(View view) {
        drawerLayoutFrame.removeAllViews();
        View layoutView;
        if (view != null) layoutView = view;
            // 若传进来的view为空，则需要单独去加载对应的view
        else layoutView = getLayoutViewByName();
        // 为重新加载的View设置相应的数据和事件监听
        resetDataAndListen(layoutView);
        drawerLayoutFrame.addView(layoutView);
    }

    /**
     * 为重新加载的View设置相应的数据和事件监听
     * view 要更新的视图文件
     */
    private void resetDataAndListen(View view) {
        if (viewText.contains("状态") || viewText.contains("界面")) {
            switch (viewText) {
                case "设备状态":
                    DeviceStatus.getInstance().setDataAndListen(mContext, view);
                    break;
                case "外设状态":
                    PeripheralStatus.getInstance().setDataAndListen(mActivity, mContext, view);
                    break;
                default:
                    break;
            }
        } else if (viewText.contains("设置")) {
            switch (viewText) {
                case "串口设置":
                    SerialPortSet.getInstance().setDataAndListen(this, mContext, view);
                    break;
                case "继电器设置":
                    RelaySet.getInstance().setDataAndListen(mContext, view);
                    break;
                case "IO设置":
                    IOSet.getInstance().setDataAndListen(mActivity, mContext, view);
                    break;
                case "图像设置":
                    ImageSet.getInstance().setDataAndListen(mContext, view);
                    break;
                case "恢复出厂设置":
                    FactoryReset.getInstance().setDataAndListen(mActivity, mContext, view);
                    break;
                case "传感器设置":
                    SensorSet.getInstance().setDataAndListen(mContext, view);
                    break;
                case "RTSP设置":
                    RTSPSet.getInstance().setDataAndListen(mActivity, mContext, view);
                    break;

                default:
                    break;
            }
        } else {
            switch (viewText) {
                case "预警记录":
                    WarningRecord.getInstance().setDataAndListen(mActivity, mContext, view, mHandler);
                    break;
                case "图像查看":
                    ImageViewer.getInstance().setDataAndListen(mActivity, mContext, view, mHandler);
                    break;
                case "配置网络":
                    Wlan.getInstance().setDataAndListen(mContext, view);
                    Intent intent = new Intent(Settings.ACTION_WIRELESS_SETTINGS);
                    intent.putExtra(":settings:show_fragment_as_subsetting", true);
                    startActivity(intent);
                    break;
                case "MQTT配置":
                    MQttConfiguration.getInstance().setDataAndListen(mContext, view);
                    break;
                case "重新开机":
                    Reboot.getInstance().setDataAndListen(mContext, view);
                    break;
                case "软件升级":
                    SoftwareUpdate.getInstance().setDataAndListen(mContext, view);
                    break;
                default:
                    break;
            }
        }
    }

    /**
     * 加载viewText对应的视图
     */
    private View getLayoutViewByName() {
        if (viewText.contains("状态") || viewText.contains("界面")) {
            switch (viewText) {
                case "设备状态":
                    return LayoutInflater.from(mContext).inflate(R.layout.frament_device_state, null, false);
                case "外设状态":
                    return LayoutInflater.from(mContext).inflate(R.layout.frament_peripheral_state, null, false);
                default:
                    return null;
            }
        } else if (viewText.contains("设置")) {
            switch (viewText) {
                case "串口设置":
                    return LayoutInflater.from(mContext).inflate(R.layout.frament_485_set, null, false);
                case "继电器设置":
                    return LayoutInflater.from(mContext).inflate(R.layout.frament_relay_set, null, false);
                case "IO设置":
                    return LayoutInflater.from(mContext).inflate(R.layout.frament_io_set, null, false);
                case "图像设置":
                    return LayoutInflater.from(mContext).inflate(R.layout.frament_image_set, null, false);
                case "恢复出厂设置":
                    return LayoutInflater.from(mContext).inflate(R.layout.frament_factory_reset, null, false);
                case "传感器设置":
                    return LayoutInflater.from(mContext).inflate(R.layout.frament_sensor_set, null, false);
                case "RTSP设置":
                    return LayoutInflater.from(mContext).inflate(R.layout.frament_rtsp_set, null, false);
                default:
                    return null;
            }
        } else {
            switch (viewText) {
                case "预警记录":
                    return LayoutInflater.from(mContext).inflate(R.layout.frament_warning_record, null, false);
                case "图像查看":
                    return LayoutInflater.from(mContext).inflate(R.layout.frament_image_viewer, null, false);
                case "配置网络":
                    return LayoutInflater.from(mContext).inflate(R.layout.frament_network_set, null, false);
                case "MQTT配置":
                    return LayoutInflater.from(mContext).inflate(R.layout.frament_mqtt_configuration, null, false);
                case "重新开机":
                    return LayoutInflater.from(mContext).inflate(R.layout.frament_reboot, null, false);
                case "软件升级":
                    return LayoutInflater.from(mContext).inflate(R.layout.frament_software_update, null, false);
                default:
                    return null;
            }
        }
    }

    @Override
    public void onBackPressed() {
        //super.onBackPressed();
    }
}